package com.itheima.utils;

import com.aliyun.oss.OSSClient;
import lombok.Data;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Data
public class AliOSSUtils {
    private AliOSSProperties aliOSSProperties;

    public String upload(MultipartFile file) throws IOException {
        String accessKeyId = aliOSSProperties.getAccessKeyId();
        String bucketName = aliOSSProperties.getBucketName();
        String endpoint = aliOSSProperties.getEndpoint();
        String accessKeySecret = aliOSSProperties.getAccessKeySecret();

        String originalFilename = file.getOriginalFilename();
        InputStream inputStream = file.getInputStream();
        String flieName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName, flieName, inputStream);
        ossClient.shutdown();
        String url = endpoint.split("//")[0] + bucketName + "." + endpoint.split("//")[1] +"/"+ flieName;
        return url;
    }
}
